<template>
  <div class="login">
    <!-- 登录表单 -->
    <el-form v-if="step === 'login'" ref="loginForm" :model="loginForm" :rules="loginRules" class="login-form">
      <h3 class="title"> {{ $t('login.title') }} <lang-select class="set-language" /></h3>
      <el-form-item prop="phone">
        <el-input ref="phone" v-model="loginForm.phone" type="text" auto-complete="off" :placeholder="$t('login.phone')">
          <svg-icon slot="prefix" icon-class="user" class="el-input__icon input-icon" />
        </el-input>
      </el-form-item>
      <el-form-item prop="password">
        <el-input
          ref="password"
          v-model="loginForm.password"
          type="password"
          auto-complete="off"
          :placeholder="$t('login.password')"
        >
          <svg-icon slot="prefix" icon-class="password" class="el-input__icon input-icon" />
        </el-input>
      </el-form-item>
      <el-form-item prop="verifyCode">
        <el-input
          ref="verifyCode"
          v-model="loginForm.verifyCode"
          auto-complete="off"
          :placeholder="$t('login.verifycode')"
          style="width: 63%"
          @keyup.enter.native="handleLogin"
        >
          <svg-icon slot="prefix" icon-class="shield" class="el-input__icon input-icon" />
        </el-input>
        <div class="login-code">
          <img :src="codeUrl" @click="getCode">
        </div>
      </el-form-item>
      <el-form-item>
        <span class="step step-login">
          <div @click="registerShow">
            {{ $t('login.registerNow') }}
          </div>
          <div @click="findPasswordShow">
            {{ $t('login.findPassword') }}
          </div>
        </span>
      </el-form-item>
      <el-form-item style="width:100%;">
        <el-button
          :loading="loading"
          size="medium"
          type="primary"
          style="width:100%;"
          @click.native.prevent="handleLogin"
        >
          <span v-if="!loading">{{ $t('login.logIn') }}</span>
          <span v-else>{{ $t('login.logIng') }}</span>
        </el-button>
      </el-form-item>
    </el-form>
    <!-- 注册表单 -->
    <el-form v-else-if="step === 'register'" ref="registerForm" :model="registerForm" :rules="registerRules" class="login-form">
      <h3 class="title"> {{ $t('login.registerTitle') }} <lang-select class="set-language" /></h3>
      <el-form-item prop="phone">
        <el-input ref="phone" v-model="registerForm.phone" type="text" auto-complete="off" :placeholder="$t('login.phone')">
          <svg-icon slot="prefix" icon-class="user" class="el-input__icon input-icon" />
        </el-input>
      </el-form-item>
      <el-form-item prop="password">
        <el-input
          ref="password"
          v-model="registerForm.password"
          type="password"
          auto-complete="off"
          :placeholder="$t('login.password')"
        >
          <svg-icon slot="prefix" icon-class="password" class="el-input__icon input-icon" />
        </el-input>
      </el-form-item>
      <el-form-item prop="smsVerifyCode">
        <el-input
          ref="smsVerifyCode"
          v-model="registerForm.smsVerifyCode"
          auto-complete="off"
          :placeholder="$t('login.verifycode')"
          @keyup.enter.native="handleRegister"
        >
          <svg-icon slot="prefix" icon-class="shield" class="el-input__icon input-icon" />
          <el-button slot="append" :disabled="count > 0" @click="getSmsCode">{{ smsText }}</el-button>
        </el-input>
      </el-form-item>
      <el-form-item>
        <span class="step" @click="loginShow">
          {{ $t('login.loginNow') }}
        </span>
      </el-form-item>
      <el-form-item style="width:100%;">
        <el-button
          :loading="loading"
          size="medium"
          type="primary"
          style="width:100%;"
          @click.native.prevent="handleRegister"
        >
          <span v-if="!loading">{{ $t('login.register') }}</span>
          <span v-else>{{ $t('login.registering') }}</span>
        </el-button>
      </el-form-item>
    </el-form>
    <!-- 找回密码表单 -->
    <el-form v-else-if="step === 'find'" ref="findForm" :model="findForm" :rules="findRules" class="login-form">
      <h3 class="title"> {{ $t('login.findTitle') }} <lang-select class="set-language" /></h3>
      <el-form-item prop="phone">
        <el-input ref="phone" v-model="findForm.phone" type="text" auto-complete="off" :placeholder="$t('login.phone')">
          <svg-icon slot="prefix" icon-class="user" class="el-input__icon input-icon" />
        </el-input>
      </el-form-item>
      <el-form-item prop="password">
        <el-input
          ref="password"
          v-model="findForm.password"
          type="password"
          auto-complete="off"
          :placeholder="$t('login.newPassword')"
        >
          <svg-icon slot="prefix" icon-class="password" class="el-input__icon input-icon" />
        </el-input>
      </el-form-item>
      <el-form-item prop="smsVerifyCode">
        <el-input
          ref="smsVerifyCode"
          v-model="findForm.smsVerifyCode"
          auto-complete="off"
          :placeholder="$t('login.verifycode')"
          @keyup.enter.native="handleFindPassword"
        >
          <svg-icon slot="prefix" icon-class="shield" class="el-input__icon input-icon" />
          <el-button slot="append" :disabled="count > 0" @click="getSmsCode">{{ smsText }}</el-button>
        </el-input>
      </el-form-item>
      <el-form-item>
        <span class="step" @click="loginShow">
          {{ $t('login.rememberNow') }}
        </span>
      </el-form-item>
      <el-form-item style="width:100%;">
        <el-button
          :loading="loading"
          size="medium"
          type="primary"
          style="width:100%;"
          @click.native.prevent="handleFindPassword"
        >
          <span v-if="!loading">{{ $t('login.findPasswordNow') }}</span>
          <span v-else>{{ $t('login.findPasswording') }}</span>
        </el-button>
      </el-form-item>
    </el-form>
    <!--  底部  -->
    <div class="el-login-footer">
      <span>Copyright © 2018-2019 ruoyi.vip All Rights Reserved.</span>
    </div>
  </div>
</template>

<script>
import LangSelect from '@/components/LangSelect'
import { getVerifyCode, sendSmsVerifyCode, findPassword } from '@/api/developer'
import { validPhone } from '@/utils/validate'

export default {
  name: 'Login',
  components: { LangSelect },
  data() {
    const validatePhone = (rule, value, callback) => {
      if (!validPhone(value)) {
        callback(new Error(this.$t('login.validatePhone')))
      } else {
        callback()
      }
    }
    const validatePassword = (rule, value, callback) => {
      if (value.length < 8 || value.length > 32) {
        callback(new Error(this.$t('login.validatePassword')))
      } else {
        callback()
      }
    }
    return {
      loginForm: {
        phone: '13111111111',
        password: '12345678',
        verifyCode: '',
        uuid: ''
      },
      loginRules: {
        phone: [{ required: true, trigger: 'blur', validator: validatePhone }],
        password: [{ required: true, trigger: 'blur', validator: validatePassword }]
      },
      registerForm: {
        phone: '',
        password: '',
        smsVerifyCode: ''
      },
      registerRules: {
        phone: [{ required: true, trigger: 'blur', validator: validatePhone }],
        password: [{ required: true, trigger: 'blur', validator: validatePassword }]
      },
      findForm: {
        phone: '',
        password: '',
        smsVerifyCode: ''
      },
      findRules: {
        phone: [{ required: true, trigger: 'blur', validator: validatePhone }],
        password: [{ required: true, trigger: 'blur', validator: validatePassword }]
      },
      smsText: this.$t('login.getSmsCode'),
      loading: false,
      redirect: undefined,
      otherQuery: {},
      codeUrl: '',
      step: 'login',
      timer: null,
      count: ''
    }
  },
  watch: {
    $route: {
      handler: function(route) {
        const query = route.query
        if (query) {
          this.redirect = query.redirect
          this.otherQuery = this.getOtherQuery(query)
        }
      },
      immediate: true
    }
  },
  created() {
    // window.addEventListener('storage', this.afterQRScan)
    this.getCode()
  },
  mounted() {
    this.focusForm()
  },
  destroyed() {
    // window.removeEventListener('storage', this.afterQRScan)
  },
  methods: {
    getCode() {
      getVerifyCode().then(res => {
        this.codeUrl = 'data:image/gif;base64,' + res.data.img
        this.loginForm.uuid = res.data.uuid
        this.loginForm.verifyCode = ''
      })
    },
    focusForm() {
      if (this.loginForm.phone === '') {
        this.$refs.phone.focus()
      } else if (this.loginForm.password === '') {
        this.$refs.password.focus()
      } else if (this.loginForm.verifyCode === '') {
        this.$refs.verifyCode.focus()
      }
    },
    focusRegisterForm() {
      // 这里条件渲染，可以用同一个ref。因为没被渲染的ref是不会被引用到的
      if (this.registerForm.phone === '') {
        this.$refs.phone.focus()
      } else if (this.registerForm.password === '') {
        this.$refs.password.focus()
      } else if (this.registerForm.smsVerifyCode === '') {
        this.$refs.smsVerifyCode.focus()
      }
    },
    handleLogin() {
      this.$refs.loginForm.validate(valid => {
        if (valid) {
          this.loading = true
          this.$store.dispatch('user/login', this.loginForm)
            .then(() => {
              this.$router.push({ path: this.redirect || '/', query: this.otherQuery })
              this.loading = false
            })
            .catch(() => {
              this.loading = false
              this.getCode()
            })
        } else {
          this.focusForm()
          console.log('error submit!!')
          return false
        }
      })
    },
    handleRegister() {
      this.$refs.registerForm.validate(valid => {
        if (valid) {
          this.loading = true
          this.$store.dispatch('user/register', this.registerForm)
            .then(() => {
              this.$router.push({ path: this.redirect || '/', query: this.otherQuery })
              this.loading = false
            })
            .catch(() => {
              this.loading = false
            })
        } else {
          this.focusRegisterForm()
          console.log('error submit!!')
          return false
        }
      })
    },
    handleFindPassword() {
      this.$refs.findForm.validate(valid => {
        if (valid) {
          this.loading = true
          findPassword(this.findForm).then(res => {
            // 成功找回。
            this.$notify({
              title: this.$t('message.success'),
              message: this.$t('login.findPassowrdSuccess'),
              type: 'success'
            })
            this.loginShow()
            this.loading = false
          }).catch(() => {
            this.loading = false
          })
        } else {
          this.focusRegisterForm()
          console.log('error submit!!')
          return false
        }
      })
    },
    getOtherQuery(query) {
      return Object.keys(query).reduce((acc, cur) => {
        if (cur !== 'redirect') {
          acc[cur] = query[cur]
        }
        return acc
      }, {})
    },
    registerShow() {
      console.log('registerShow')
      this.registerForm = {
        phone: '',
        password: '',
        smsVerifyCode: ''
      }
      this.step = 'register'
    },
    loginShow() {
      console.log('loginShow')
      this.loginForm = {
        phone: '',
        password: '',
        verifyCode: '',
        uuid: ''
      }
      this.getCode()
      this.step = 'login'
    },
    findPasswordShow() {
      console.log('findPasswordShow')
      this.findForm = {
        phone: this.loginForm.phone ? this.loginForm.phone : '',
        password: '',
        smsVerifyCode: ''
      }
      this.step = 'find'
    },

    getSmsCode() {
      let formObj
      if (this.$refs.registerForm) {
        formObj = this.registerForm
      } else {
        formObj = this.findForm
      }
      if (formObj.phone && (validPhone(formObj.phone))) {
        sendSmsVerifyCode(formObj.phone).then(res => {
          // 发送验证码
          this.$notify({
            title: this.$t('message.success'),
            message: this.$t('login.sendVerifyCodeSuccess'),
            type: 'success'
          })
          const TIME_COUNT = 60
          if (!this.timer) {
            this.count = TIME_COUNT
            this.smsText = this.count + this.$t('login.retrySmsCode')
            this.timer = setInterval(() => {
              if (this.count > 0 && this.count <= TIME_COUNT) {
                this.count--
                this.smsText = this.count + this.$t('login.retrySmsCode')
              } else {
                this.count = 0
                this.smsText = '重新获取'
                clearInterval(this.timer)
                this.timer = null
              }
            }, 1000)
          }
        })
      } else {
        this.$notify({
          title: this.$t('message.fail'),
          message: this.$t('login.completePhone'),
          type: 'error'
        })
      }
    }
  }
}
</script>

<style lang="scss">
.login {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100%;
  background-image: url("../../assets/login-background.jpg");
  background-size: cover;
}

.title {
  margin: 0px auto 30px auto;
  text-align: center;
  color: #707070;
}

.login-form {
  z-index: 99;
  border-radius: 6px;
  background: #ffffff;
  width: 400px;
  padding: 25px 25px 5px 25px;
  .el-input {
    height: 38px;
    input {
      height: 38px;
    }
  }
  .input-icon {
    height: 39px;
    width: 14px;
    margin-left: 2px;
  }

}

.set-language {
    font-size: 18px;
    float: right;
  }

.login-tip {
  font-size: 13px;
  text-align: center;
  color: #bfbfbf;
}
.login-code {
  width: 33%;
  height: 38px;
  float: right;
  img {
    cursor: pointer;
    vertical-align: middle;
  }
}
.el-login-footer {
  z-index: 99;
  height: 40px;
  line-height: 40px;
  position: fixed;
  bottom: 0;
  width: 100%;
  text-align: center;
  color: #fff;
  font-family: Arial;
  font-size: 12px;
  letter-spacing: 1px;
}
.step {
  color: #666666;
  text-decoration: underline;
}
.step-login {
  display: flex;
  justify-content: space-between;
}

</style>
